﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Resources;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Converter;
using csla4Skeleton.UI.SL.Resources.Utility;
using csla4Skeleton.UI.SL.NghiepVu.THUE.THUE_BangKeBanRa;
using csla4Skeleton.UI.SL.NghiepVu.THUE.THUE_BangKeMuaVao;
using csla4Skeleton.UI.SL.TongHop.TH_SoDuTK;
using csla4Skeleton.UI.SL.DanhMuc.DM_TaiKhoan;
using Accounting.Library;
using Telerik.Windows.Controls;
using Telerik.Windows.Controls.GridView;
using System.ComponentModel;
using Utility;
using Accounting.Library.Utility;

namespace csla4Skeleton.UI.SL.NghiepVu.THUE.THUE_KhauTru
{
    public partial class THUE_KhauTru_ChildWindow : ChildWindow, Csla.Xaml.ISupportNavigation
    {

        #region ISupportNavigation Members
        List<Control> controls = new List<Control>();

        private System.Nullable<double> a = null;
        private System.Nullable<double> b = null;
        private System.Nullable<double> c = null;
        private System.Nullable<double> d = null;

        public string Result = "";

        public bool CreateBookmarkAfterLoadCompleted
        {
            get { return true; }
        }

        public event EventHandler LoadCompleted;
        public event EventHandler Saved;
        protected virtual void OnLoadCompleted()
        {
            if (LoadCompleted != null)
                LoadCompleted(this, EventArgs.Empty);
        }

        public void SetParameters(string parameters)
        {
            try
            {
                if (parameters == "")
                    Khoa = null;
                else
                    Khoa = Int32.Parse(parameters);
            }
            catch
            {
                Khoa = null;
            }
        }

        public string Title
        {
            get { return "KhauTru"; }
        }

       
        #endregion

        #region Load Methods
        private System.Nullable<int> Khoa = null;
        private int Thang ;
        private int Nam;

        public int countSave = 0;
        public event EventHandler OnClosedChildWindow;
        
        public event EventHandler TinhKhauTruCompleteted;
        public event EventHandler SaveCompleteted;
        public IList<TH_SoChiTietInfo> listSoChiTiet;

        public THUE_KhauTru_ChildWindow(int Khoa)          
        {
            this.Khoa = Khoa;

            LocalizationConverter converter = new LocalizationConverter();
            converter.LocalResourceManager = new ResourceManager("csla4Skeleton.UI.SL.NghiepVu.THUE.THUE_KhauTru.Resources", Assembly.GetExecutingAssembly());
            this.Resources.Add("Localization", converter);

            InitializeComponent();
            ControlBehavior.ControlBehaviors.Navigation(this.THUE_KhauTru_ChungTuInformation_GroupBox, controls);
        }

        public THUE_KhauTru_ChildWindow()
        {
            LocalizationConverter converter = new LocalizationConverter();
            converter.LocalResourceManager = new ResourceManager("csla4Skeleton.UI.SL.NghiepVu.THUE.THUE_KhauTru.Resources", Assembly.GetExecutingAssembly());
            this.Resources.Add("Localization", converter);
            
            InitializeComponent();  
            ControlBehavior.ControlBehaviors.Navigation(this.THUE_KhauTru_ChungTuInformation_GroupBox, controls);
           
        }
        public THUE_KhauTru_ChildWindow(string thang, string nam)
        {
            LocalizationConverter converter = new LocalizationConverter();
            converter.LocalResourceManager = new ResourceManager("csla4Skeleton.UI.SL.NghiepVu.THUE.THUE_KhauTru.Resources", Assembly.GetExecutingAssembly());
            this.Resources.Add("Localization", converter);

            InitializeComponent();
            ControlBehavior.ControlBehaviors.Navigation(this.THUE_KhauTru_ChungTuInformation_GroupBox, controls);

            this.Thang = int.Parse(thang);
            this.Nam = int.Parse(nam);
           
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            if (!System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
            {

                System.Windows.Data.CollectionViewSource THUE_KhauTru_CollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["THUE_KhauTru_ViewModelSource"];
                if (Khoa == null)
                {
                    THUE_KhauTru_ViewModel THUE_KhauTru_ViewModel = new THUE_KhauTru_ViewModel();
                    THUE_KhauTru_ViewModel.ChildList_AddedNew += new THUE_KhauTru_ViewModel.ChildList_AddedNew_EventHandler(THUE_KhauTru_ViewModel_ChildList_AddedNew);              
                    
                    THUE_KhauTru_ViewModel.LoadCompleted += new EventHandler(THUE_KhauTru_ViewModel_LoadCompleted);
                    THUE_KhauTru_ViewModel.Saved += new EventHandler(OnSaveCompleted);

                    THUE_KhauTru_ViewModel.CountChanged += new EventHandler(OnCountChanged);  
                    THUE_KhauTru_CollectionViewSource.Source = new List<object> { THUE_KhauTru_ViewModel };

               
                    
                    
                }
                else
                {
                    THUE_KhauTru_ViewModel THUE_KhauTru_ViewModel = new THUE_KhauTru_ViewModel((int)Khoa);
                    THUE_KhauTru_ViewModel.ChildList_AddedNew += new THUE_KhauTru_ViewModel.ChildList_AddedNew_EventHandler(THUE_KhauTru_ViewModel_ChildList_AddedNew);
                    
                    THUE_KhauTru_ViewModel.Saved += new EventHandler(OnSaveCompleted);
                    THUE_KhauTru_CollectionViewSource.Source = new List<object> { THUE_KhauTru_ViewModel };
                    
                }

                System.Windows.Data.CollectionViewSource DM_TaiKhoan_CollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["DM_TaiKhoan_ListViewModelSource"];
                DM_TaiKhoan_ListViewModel dm_TaiKhoan_ListViewModel = new DM_TaiKhoan_ListViewModel(BusinessConfiguration.Configuration.ComboboxFetchMode);
                DM_TaiKhoan_CollectionViewSource.Source = new List<object> { dm_TaiKhoan_ListViewModel };
                   
                this.THUE_KhauTru_KhauTruChiTietGridView.KeyboardCommandProvider = new ControlBehavior.GridViewKeyboardCommandProvider(this.THUE_KhauTru_KhauTruChiTietGridView);
                
                ((ControlBehavior.GridViewKeyboardCommandProvider)this.THUE_KhauTru_KhauTruChiTietGridView.KeyboardCommandProvider).ReachLastColumn += new ControlBehavior.GridViewKeyboardCommandProvider.ReachLastColumn_EventHandler(OnReachLastColumn);

                ((ControlBehavior.GridViewKeyboardCommandProvider)this.THUE_KhauTru_KhauTruChiTietGridView.KeyboardCommandProvider).TabKeyPress += new EventHandler(OnTabKeyPress);
            }
        }

        #endregion
       

        #region Event Handle
        private void LayoutRoot_KeyUp(object sender, KeyEventArgs e)
        {
            if (Keyboard.Modifiers == ModifierKeys.Control)
            {
                THUE_KhauTru_ViewModel vm = GetViewModel();
                if (e.Key == Key.S)
                {
                    if (vm.CanSave)
                    {
                        vm.Save(sender, new Csla.Xaml.ExecuteEventArgs());
                    }
                }
                else if (e.Key == Key.F6)
                {
                    AddItems();
                }
                else if (e.Key == Key.D1)
                {
                    this.THUE_KhauTru_KhauTruChiTietTab.IsSelected = true;
                }
               
               
                
            }
            e.Handled = true;
        }

        void AddItemButton_Click(object sender, RoutedEventArgs e)
        {

            AddItems();
        }

        void DeleteItemButton_Click(object sender, RoutedEventArgs e)
        {
            DeleteItems();
          
        }

        public void AddItems()
        {
            if (this.THUE_KhauTru_KhauTruChiTietTab.IsSelected)
            {
                AddKhauTruDetailsItem();
            }
        }
        private RadGridView GetActiveGridView()
        {
            if (this.THUE_KhauTru_KhauTruChiTietTab.IsSelected)
            {
                return THUE_KhauTru_KhauTruChiTietGridView;
            }
           
            return null;
        }

        void DeleteItems()
        {
           if (this.THUE_KhauTru_KhauTruChiTietTab.IsSelected)
            {
                THUE_KhauTru_ChiTietChild ChiTietChild = (THUE_KhauTru_ChiTietChild)(this.THUE_KhauTru_KhauTruChiTietGridView.SelectedItem);
                IList<THUE_KhauTru_ChiTietChild> list = GetViewModel().Model.THUE_KhauTru_ChiTiets;
                int index = list.IndexOf(ChiTietChild);
                
                DeleteKhauTruDeTailsItem(index);
            }
           
            
        }
           
        void GridView_AddingNewDataItem(object sender, GridViewAddingNewEventArgs e)
        {
            var grid = e.OwnerGridViewItemsControl;
            if (grid.Items.Count > 0)
            {
                GridViewUtil.FocusRow((RadGridView)grid, grid.Items.Count - 1);
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    grid.CurrentCellInfo = new GridViewCellInfo(grid.Items[grid.Items.Count - 1], grid.Columns[0]);
                    grid.Focus();
                    grid.BeginEdit();
                }));
            }
        }
              
        private void SaveAndNewButton_Click(object sender, RoutedEventArgs e)
        {
           THUE_KhauTru_ViewModel vm = GetViewModel();
            vm.SaveAndNew();
        }

        private void DatePicker_KeyUp(object sender, KeyEventArgs e)
        {
            List<Control> availableControl = new List<Control>();
            foreach (Control item in controls)
            {
                if (item.Visibility == System.Windows.Visibility.Visible)
                {
                    availableControl.Add(item);
                }
            }
            Control[] list = availableControl.ToArray();
            if (sender.GetHashCode() == list[availableControl.Count - 1].GetHashCode())
            {
                if (e.Key == Key.Enter)
                {
                    this.AddKhauTruDetailsItem();
                }
            }
            else
            {
                ControlBehavior.DatePickerBehaviors.DatePicker_KeyUp(sender, e, controls);
            }
        }

        private void ComboBox_KeyUp(object sender, KeyEventArgs e)
        {
            List<Control> availableControl = new List<Control>();
            foreach (Control item in controls)
            {
                if (item.Visibility == System.Windows.Visibility.Visible)
                {
                    availableControl.Add(item);
                }
            }
            Control[] list = availableControl.ToArray();
            if (sender.GetHashCode() == list[availableControl.Count - 1].GetHashCode())
            {
                if (e.Key == Key.Enter)
                {
                    this.AddKhauTruDetailsItem();
                }
            }
            else
            {
                ControlBehavior.ComboBoxBehaviors.ComboBox_KeyUp(sender, e, controls);
            }
        }

        private void Control_KeyUp(object sender, KeyEventArgs e)
        {
            List<Control> availableControl = new List<Control>();
            foreach (Control item in controls)
            {
                if (item.Visibility == System.Windows.Visibility.Visible)
                {
                    availableControl.Add(item);
                }
            }
            Control[] list = availableControl.ToArray();
            if (sender.GetHashCode() == list[availableControl.Count - 1].GetHashCode())
            {
                if (e.Key == Key.Enter)
                {
                    this.AddKhauTruDetailsItem();
                }
            }
            else
            {
                ControlBehavior.ControlBehaviors.Control_KeyUp(sender, e, controls);
            }
        }


        private void BookedItemButton_Click(object sender, RoutedEventArgs e)
        {
            GetViewModel().GhiSo();
        }

        private void DeleteBookedItemButton_Click(object sender, RoutedEventArgs e)
        {
            GetViewModel().BoGhi();
        }

        void OnTabKeyPress(object sender, EventArgs e)
        {
            this.tabControl.SelectedItem = tabControl.Items[0];
            this.AddKhauTruDetailsItem();
        }

        void OnReachLastColumn(object sender, ReachLastColumnArgs e)
        {

            List<TabItem> AvailableTabItem = new List<TabItem>();
            int indexCurrentTab = 0;
            foreach (TabItem item in this.tabControl.Items)
            {
                if (item.Visibility == System.Windows.Visibility.Visible)
                {
                    AvailableTabItem.Add(item);
                    if (item.GetHashCode() == tabControl.SelectedItem.GetHashCode())
                    {
                        indexCurrentTab = AvailableTabItem.IndexOf(item);
                    }

                }
            }


            TabItem[] list = AvailableTabItem.ToArray();
            if (indexCurrentTab == (AvailableTabItem.Count - 1))
            {
                this.tabControl.SelectedItem = list[0];
                FocusAfterChangeTab(this.THUE_KhauTru_KhauTruChiTietGridView, e.Index);

            }
            

        }

        private void FocusAfterChangeTab(GridViewDataControl grid, int index)
        {
             
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    grid.CurrentCellInfo = new GridViewCellInfo(grid.Items[index], grid.Columns[0]);
                    grid.Focus();
                    grid.BeginEdit();
                }));
           
        }
        
        
       
        #endregion

        #region View Model Related Methods
        public THUE_KhauTru_ViewModel GetViewModel()
        {
            System.Windows.Data.CollectionViewSource THUE_KhauTru_CollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["THUE_KhauTru_ViewModelSource"];
            return ((List<object>)THUE_KhauTru_CollectionViewSource.Source)[0] as THUE_KhauTru_ViewModel;
        }

        private void THUE_KhauTru_ViewModel_LoadCompleted(object sender, EventArgs e)
        {
            System.Windows.Data.CollectionViewSource THUE_BangKeBanRa_CollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["THUE_BangKeBanRa_ListViewModelSource"];
            THUE_BangKeBanRa_ListViewModel thue_BangKeBanRa_ListViewModel = new THUE_BangKeBanRa_ListViewModel(this.Thang, this.Nam);
            thue_BangKeBanRa_ListViewModel.LoadCompleted += new EventHandler(OnBangKeBanRaAndKhauTruLoadCompleteted);
            THUE_BangKeBanRa_CollectionViewSource.Source = new List<object> { thue_BangKeBanRa_ListViewModel };
        }

        private void OnBangKeBanRaAndKhauTruLoadCompleteted(object sender, EventArgs e)
        {
            System.Windows.Data.CollectionViewSource THUE_BangKeMuaVao_CollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["THUE_BangKeMuaVao_ListViewModelSource"];
            THUE_BangKeMuaVao_ListViewModel thue_BangKeMuaVao_ListViewModel = new THUE_BangKeMuaVao_ListViewModel(this.Thang, this.Nam);
            thue_BangKeMuaVao_ListViewModel.LoadCompleted += new EventHandler(OnBangKeBanRaAndMuaVaoAndKhauTruLoadCompleteted);
            THUE_BangKeMuaVao_CollectionViewSource.Source = new List<object> { thue_BangKeMuaVao_ListViewModel };
        }
      
        private void OnBangKeBanRaAndMuaVaoAndKhauTruLoadCompleteted(object sender, EventArgs e)
        {

            System.Windows.Data.CollectionViewSource TH_SoDuTK_CollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["TH_SoDuTK_ListViewModelSource"];
            TH_SoDuTK_ListViewModel th_SoDuTK_ListViewModel = new TH_SoDuTK_ListViewModel(this.Thang, this.Nam);
            th_SoDuTK_ListViewModel.LoadCompleted += new EventHandler(OnAllListLoadCompleted);
            TH_SoDuTK_CollectionViewSource.Source = new List<object> { th_SoDuTK_ListViewModel };
        }

      
        private void OnAllListLoadCompleted(object sender, EventArgs e)
        {
            this.GetViewModel().Model.Thang = this.Thang;
            this.GetViewModel().Model.Nam = this.Nam;

            System.Windows.Data.CollectionViewSource THUE_BangKeBanRa_CollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["THUE_BangKeBanRa_ListViewModelSource"];
            THUE_BangKeBanRa_ListViewModel thue_BangKeBanRa_ListViewModel = ((List<object>)THUE_BangKeBanRa_CollectionViewSource.Source)[0] as THUE_BangKeBanRa_ListViewModel;
            IList<THUE_BangKeBanRaInfo> listBangKeBanRa = thue_BangKeBanRa_ListViewModel.Model.getListOfInfo();
            

            System.Windows.Data.CollectionViewSource THUE_BangKeMuaVao_CollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["THUE_BangKeMuaVao_ListViewModelSource"];
            THUE_BangKeMuaVao_ListViewModel thue_BangKeMuaVao_ListViewModel = ((List<object>)THUE_BangKeMuaVao_CollectionViewSource.Source)[0] as THUE_BangKeMuaVao_ListViewModel;
            IList<THUE_BangKeMuaVaoInfo> listBangKeMuaVao = thue_BangKeMuaVao_ListViewModel.Model.getListOfInfo();
           

            System.Windows.Data.CollectionViewSource TH_SoDuTK_CollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["TH_SoDuTK_ListViewModelSource"];
            TH_SoDuTK_ListViewModel th_SoDuTK_ListViewModel = ((List<object>)TH_SoDuTK_CollectionViewSource.Source)[0] as TH_SoDuTK_ListViewModel;
            IList<TH_SoDuTKInfo> listSoDuTK = th_SoDuTK_ListViewModel.Model.getListOfInfo();
            
            if(listBangKeBanRa.Count != 0)
            {
                THUE_BangKeBanRaInfo[] BangKeBanRaArray = new THUE_BangKeBanRaInfo[listBangKeBanRa.Count];
                listBangKeBanRa.CopyTo(BangKeBanRaArray,0);
                b = BangKeBanRaArray[0].TongTienThue;
            }
            if(listBangKeMuaVao.Count != 0)
            {
                THUE_BangKeMuaVaoInfo[] BangKeMuaVaoArray = new THUE_BangKeMuaVaoInfo[listBangKeMuaVao.Count];
                listBangKeMuaVao.CopyTo(BangKeMuaVaoArray,0);
                a = BangKeMuaVaoArray[0].TongTienThue;
            }
            
            foreach(TH_SoDuTKInfo item in listSoDuTK)
            {
                if (item.TkCon.Equals("133"))
                {
                    c = item.DuNo;
                }
                else if (item.TkCon.Equals("3331"))
                {
                    d = item.DuCo;
                }
                
            }

            if (a != null && b != null && c != null && d != null)
            {
                if (((a + c) == 0) || ((b + d) == 0))
                {
                    Result = "Không thực hiện khấu trừ thuế được vì không có phát sinh trong kỳ";
                   
                    if (TinhKhauTruCompleteted != null)
                    {
                        TinhKhauTruCompleteted(this, new EventArgs());

                    }
                }
                else if ((a + c) == (b + d))
                {
                    Result = "Không phát sinh bút toán khấu trừ vì thuế đầu vào và đầu ra bằng nhau";
                    
                    if (TinhKhauTruCompleteted != null)
                    {
                        TinhKhauTruCompleteted(this, new EventArgs());

                    }
                }
                else if ((a + c) > (b + d))
                {
                    this.AddKhauTruDetailsItem();
                }
                else if ((a + c) < (b + d))
                {
                    this.AddKhauTruDetailsItem();
                }
            }
            else
            {
                Result = "Số liệu để khấu trừ chưa có đủ trong tháng này";
               
                if (TinhKhauTruCompleteted != null)
                {
                    TinhKhauTruCompleteted(this, new EventArgs());

                }
            }
           
            
        }

        private void OnCountChanged(object sender, EventArgs e)
        {

                System.Windows.Data.CollectionViewSource DM_TaiKhoan_CollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["DM_TaiKhoan_ListViewModelSource"];
                DM_TaiKhoan_ListViewModel dm_TaiKhoan_ListViewModel = ((List<object>)DM_TaiKhoan_CollectionViewSource.Source)[0] as DM_TaiKhoan_ListViewModel;
                IList<DM_TaiKhoanInfo> listTaiKhoan = dm_TaiKhoan_ListViewModel.Model.getListOfInfo();

                if( this.GetViewModel().Model.THUE_KhauTru_ChiTiets.Count != 0)
                {
                    int index = this.GetViewModel().Model.THUE_KhauTru_ChiTiets.Count - 1;
                    this.GetViewModel().Model.THUE_KhauTru_ChiTiets[index].DienGiai = "Bút toán khấu trừ thuế GTGT tháng "+this.Thang +" năm "+ this.Nam;
                    foreach ( DM_TaiKhoanInfo item in listTaiKhoan)
                    {
                        if(item.Ma.Equals("3331"))
                        {
                             this.GetViewModel().Model.THUE_KhauTru_ChiTiets[index].TKNoId = item.Khoa;
                        }
                        else if (item.Ma.Equals("133"))
                        {
                            this.GetViewModel().Model.THUE_KhauTru_ChiTiets[index].TKCoId = item.Khoa;
                        }
                    }
                    if(( a + c ) > (b + d))
                    {
                        this.GetViewModel().Model.THUE_KhauTru_ChiTiets[index].SoTien = (b +d);
                        this.GetViewModel().Model.TinhTongTien();
                        this.GetViewModel().Save(this, new Csla.Xaml.ExecuteEventArgs());
                    }
                    else if (( a + c ) < (b + d))
                    {
                        this.GetViewModel().Model.THUE_KhauTru_ChiTiets[index].SoTien = (a +c);
                        this.GetViewModel().Model.TinhTongTien();
                        this.GetViewModel().Save(this, new Csla.Xaml.ExecuteEventArgs());
                    }
                }
        }
            
        private void OnSaveCompleted(object sender, EventArgs e)
        {
            
            if (TinhKhauTruCompleteted != null)
            {
                TinhKhauTruCompleteted(this, new EventArgs());
                
            }
        }

        protected override void OnClosed(EventArgs e)
        {
            if (OnClosedChildWindow != null)
            {
                OnClosedChildWindow(this, new EventArgs());
            }
            base.OnClosed(e);
            
        }
        private void AddKhauTruDetailsItem()
        {
            GetViewModel().AddTHUE_KhauTru_ChiTietItem();
        }
        private void DeleteKhauTruDeTailsItem(int Index)
        {
            GetViewModel().DeleteTHUE_KhauTru_ChiTietItem( Index);
        }

        void THUE_KhauTru_ViewModel_ChildList_AddedNew(object sender, ChildListAddedNewArgs e)
        {
            if (e.ChildListName == "THUE_KhauTru_ChiTiets")
            {
                this.THUE_KhauTru_KhauTruChiTietGridView.OnAddingNewDataItem(new GridViewAddingNewEventArgs(GetActiveGridView()));
            }
        }

       
        #endregion
        
    }
}
